import logging
import sys
from pathlib import Path


def setup_logger(name: str, level=logging.INFO) -> logging.Logger:
    """
    设置并返回一个logger实例

    Args:
        name: logger名称，通常使用 __name__
        level: 日志级别

    Returns:
        logging.Logger: 配置好的logger实例
    """
    # 创建logger
    logger = logging.getLogger(name)
    logger.setLevel(level)

    # 如果已经配置过handler，直接返回
    if logger.handlers:
        return logger

    # 创建formatter
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )

    # 创建控制台handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(formatter)

    # 创建文件handler
    log_dir = Path(__file__).parent.parent / "logs"
    log_dir.mkdir(exist_ok=True)

    file_handler = logging.FileHandler(log_dir / "app.log", encoding='utf-8')
    file_handler.setFormatter(formatter)

    # 添加handler到logger
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)

    return logger


# 为直接运行此文件提供测试
if __name__ == "__main__":
    test_logger = setup_logger(__name__)
    test_logger.info("Logger配置测试成功")